package org.opencv.LoadObj;

import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;

import android.util.Log;

public class LoadObjDetector {
	static private final String TAG = "Opencv:LoadObjDetector";

	public LoadObjDetector() {
		// mNativeObj = nativeCreateObject(width,height);
		// System.loadLibrary("native_LoadObj");
	}

	public void release() {
		nativeDestroyObject(mNativeObj);
		mNativeObj = 0;
	}

	public void InitObj(int width, int height) {
		mNativeObj = nativeCreateObject(width, height);
	}

	public int detect(Mat imgRGBA, MatOfRect objMat) {
		bEnableSensor = true;
		return nativeDetect(mNativeObj, imgRGBA.getNativeObjAddr(),
				objMat.getNativeObjAddr());
	}

	public boolean motionDetect(Mat imgRGBA) {
		bEnableSensor = true;
		return nativeMotionDetect(mNativeObj, imgRGBA.getNativeObjAddr());
	}

	public int getObjInfo(MatOfRect objMat) {
		if (objMat.empty())
			return 0;
		Rect[] objArray = objMat.toArray();
		return objArray.length - 1;
	}

	public void BorderAlarm(Mat imgRGBA, MatOfRect borderMat) {
		// MatOfRect borderMat = new MatOfRect();
		if (BGFinishUpdate()) {
			nativeBorderAlarm(mNativeObj, imgRGBA.getNativeObjAddr(),
					borderMat.getNativeObjAddr());
		}
	}

	public int getBorderInfo(MatOfRect borderMat) {
		int borderOri = -1;
		if (borderMat.empty())
			borderOri = -1;
		Rect[] borderArray = borderMat.toArray();
		for (int i = 0; i < borderArray.length; i++) {
			int horDir = borderArray[i].width;
			int verDir = borderArray[i].height;
			if (-1 != horDir)
				borderOri = horDir;
			else if (-1 != verDir)
				borderOri = verDir + 2;
			else
				borderOri = -1;
		}
		return borderOri;
	}

	public void SetAlarmRegion(int pt1x, int pt1y, int pt2x, int pt2y) {

		nativeSetAlarmRegion(mNativeObj, pt1x, pt1y, pt2x, pt2y);

	}

	public boolean BGFinishUpdate() {
		return nativeBGUpdate(mNativeObj);
	}

	public void SetBGMat(Mat matBG) {
		nativeResetBG(mNativeObj, matBG.getNativeObjAddr());
	}

	public void BGResetShake() {
		nativeBGResetShake(mNativeObj);
	}

	public boolean IsSensorEnable() {
		return bEnableSensor;
	}

	private long mNativeObj = 0;
	private boolean bEnableSensor = false;

	private static native long nativeCreateObject(int width, int height);

	private static native void nativeDestroyObject(long thiz);

	private static native boolean nativeMotionDetect(long thiz, long inputRGBA);

	private static native int nativeDetect(long thiz, long inputRGBA,
			long objMat);

	private static native int nativeBorderAlarm(long thiz, long inputRGBA,
			long objMat);

	private static native void nativeSetAlarmRegion(long thiz, int pt1x,
			int pt1y, int pt2x, int pt2y);

	private static native void nativeResetBG(long thiz, long matBG);

	private static native void nativeBGResetShake(long thiz);

	private static native boolean nativeBGUpdate(long thiz);
}
